package simple

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
)

type FileCallback func(line string, name string)

type FileProcess struct {
	Root     string
	Callback FileCallback
}

// FileWalk 回调处理
func (ux *FileProcess) FileWalk(path string, file os.FileInfo, err error) error {
	if file.IsDir() {
		println("This is folder:(" + path + ")")
	} else {
		if strings.Contains(path, "info.log.") {
			rd, err := os.Open(path)
			if err != nil {
				panic("open failed!")
			}
			defer rd.Close()

			count := 0
			b := bufio.NewReader(rd)
			line := ""
			for ; err == nil; line, err = b.ReadString('\n') {
				count++
				cntStr := fmt.Sprintf(" (R:%6d) ", count)
				ux.Callback(ux.ConvertGBK2Str(line), file.Name()+cntStr)
			}
		}
	}
	return nil
}

// StartWalk 开始变量
func (ux *FileProcess) StartWalk() {
	t := time.Now()
	err := filepath.Walk(ux.Root, ux.FileWalk)
	if err != nil {
		fmt.Printf("filepath.Walk() error: %v\n", err)
	}
	fmt.Println("walk: " + time.Now().Sub(t).String())
	return
}

func (ux *FileProcess) ConvertGBK2Str(gbkStr string) string {
	return gbkStr
}
